package net.scalan.jpa.model;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.EntityNotFoundException;
import net.scalan.jpa.Common;
import net.scalan.jpa.exceptions.NonexistentEntityException;

/**
 *
 * @author scalan
 */
public class DBTestController {

    public DBTestController() {
        emf = Persistence.createEntityManagerFactory(Common.EntityManagerFactoryName);
    }

    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(DBTest data) {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            em.persist(data);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void update(DBTest data) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            data = em.merge(data);
            em.getTransaction().commit();
        } catch (Exception ex) {
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void delete(Long id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            DBTest data;
            try {
                data = em.getReference(DBTest.class, id);
                data.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The DBTest with id " + id + " no longer exists.", enfe);
            }
            em.remove(data);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public DBTest getObject(Long id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(DBTest.class, id);
        } finally {
            em.close();
        }
    }

}
